import { command, model } from '@/ts/base';
import { DataProvider } from '.';
import { IFile, ITarget, XObject } from '..';
import { IBelong } from '../target/base/belong';
import { Xbase } from '@/ts/base/schema';

declare const dd: {
  setStorageSync: (option: { key: string; data: string }) => void;
};

/** 主页方法提供者 */
export class HomeProvider {
  private userId: string;
  private _userSetting: boolean = false;
  private data: DataProvider;
  private cacheObj: XObject<Xbase>;
  private _selectSpace: IBelong;
  public homeConfig: model.HomeConfig;
  public commons: IFile[] = [];
  constructor(_data: DataProvider) {
    this.data = _data;
    this.userId = _data.user!.id;
    this.cacheObj = _data.user!.cacheObj;
    this._selectSpace = _data.user!;
    this.homeConfig = { tops: [] };
  }

  get isUser(): boolean {
    return this._userSetting || this.current.id === this.userId;
  }
  get current(): IBelong {
    return this._userSetting ? this.data.user! : this._selectSpace;
  }
  get selectSpace(): IBelong {
    return this._selectSpace;
  }
  commentsFlag(belong?: IBelong): string {
    belong = belong ?? this.current;
    return belong.id === this.userId ? '_commons' : `_${belong.id}commons`;
  }
  targets(belong?: IBelong): ITarget[] {
    belong = belong ?? this.current;
    return belong.id === this.userId ? this.data.targets : belong.targets;
  }
  async switchSpace(
    space: IBelong = this._selectSpace,
    userSetting: boolean = false,
  ): Promise<void> {
    this._userSetting = userSetting;
    if (!userSetting && space != this._selectSpace) {
      this._selectSpace = space;
      this.cacheObj.set('homeLastSpaceId', space.id);
    }
    this.commons = [];
    this.homeConfig = (await this.current.cacheObj.get('homeConfig')) || { tops: [] };
    command.emitterFlag('topChanged', 'start');
  }
  findLastSpace(lastSpaceId: string): IBelong | undefined {
    return this.data.spaces.find((i) => i.id === lastSpaceId);
  }
  async loadConfig(): Promise<void> {
    const layout = await this.cacheObj.get<string>('toolbarLayout');
    const layoutValue = layout ?? 'top';
    this.saveToolbarLayout(layoutValue);
    const lastSpaceId = await this.cacheObj.get<string>('homeLastSpaceId');
    if (lastSpaceId) {
      const lastSpace = this.findLastSpace(lastSpaceId);
      if (lastSpace) {
        this._selectSpace = lastSpace;
      }
    }
    const cache = await this.current.cacheObj.get<model.HomeConfig>('homeConfig');
    if (cache?.tops) {
      this.homeConfig = cache;
    }
    command.emitterFlag('topChanged', 'start');
  }
  async switchTops(id: string) {
    const isSave = this.homeConfig.tops?.find((i) => i === id);
    if (!!isSave) {
      this.homeConfig.tops = this.homeConfig.tops.filter((i) => i !== id);
    } else {
      this.homeConfig.tops.push(id);
    }
    command.emitterFlag('topChanged', 'end');
    return await this.current.cacheObj.set('homeConfig', this.homeConfig);
  }

  private saveToolbarLayout(layoutValue: string): void {
    // #ifdef MP-DINGTALK
    dd.setStorageSync({ key: 'toolbarLayout', data: layoutValue });
    // #endif
    // #ifdef H5
    localStorage.setItem('toolbarLayout', layoutValue);
    // #endif
    // #ifndef H5
    uni.setStorageSync('toolbarLayout', layoutValue);
    // #endif
  }

  async loadCommons(belong?: IBelong): Promise<IFile[]> {
    const files: IFile[] = [];
    belong = belong ?? this.current;
    for (const item of belong.commons) {
      const target = this.targets(belong).find(
        (i) => i.id === item.targetId && i.spaceId === item.spaceId,
      );
      if (target) {
        const file = await target.directory.searchComment(item);
        if (file && ('isAuth' in file ? file.isAuth : true)) {
          if (file.groupTags.includes('已删除')) {
            belong.updateCommon(item, false);
          } else {
            files.push(file);
          }
        }
      }
    }
    if (belong.id === this.current.id) {
      this.commons = files;
      command.emitterFlag('topChanged', 'end');
    }
    return files;
  }
}
